<template>
  <view class="event-container">
    <view class="empty-tip" v-if="displayEvents.length === 0">
      <image class="empty-icon" src="/static/data-empty.png" mode="aspectFit"></image>
      <text class="empty-text">暂无事件数据</text>
    </view>

    <view 
      class="event-card" 
      v-for="(event, index) in displayEvents" 
      :key="event.id"
      @tap="onEventClick(event)"
    >
      <view class="event-header">
        <view class="event-title">{{ event.eventName }}</view>
        <view class="event-tags">
          <view class="event-tag type-tag">
            <uni-icons v-if="getEventIcon(event.type)" :type="getEventIcon(event.type)" size="14" color="#007AFF"></uni-icons>
            <text>{{ event.type || getCategoryName(event.categoryId) }}</text>
          </view>
          <view class="event-tag" :class="getStatusClass(event.dealStatus)">
            {{ getStatusText(event.dealStatus) }}
          </view>
        </view>
      </view>
      
      <view class="event-content">
        <view class="event-desc">{{ event.eventContent }}</view>
      </view>
      
      <view class="event-footer">
        <text class="event-time">{{ formatEventDate(event.eventDate) }}</text>
        <view class="event-info">
          <view class="event-reminder" v-if="event.reminderEnabled === 1">
            <uni-icons type="notification" size="12" color="#999"></uni-icons>
            <text>{{ formatReminder(event) }}</text>
          </view>
          <view class="event-repeat" v-if="event.repeatType > 0">
            <uni-icons type="loop" size="12" color="#999"></uni-icons>
            <text>{{ getRepeatTypeText(event.repeatType) }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <view class="add-button" @tap="addEvent">
      <uni-icons type="plusempty" size="24" color="#FFFFFF"></uni-icons>
    </view>
  </view>
</template>

<script setup>
import { ref, defineEmits, onMounted, watch, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import EventApi from '@/pages/contact/api/event';

const props = defineProps({
  events: {
    type: Array,
    default: () => []
  },
  contactId: {
    type: String,
    default: ''
  },
  currentTab: {
    type: Number,
    default: 0
  },
  tabIndex: {
    type: Number,
    default: 2
  }
});

const emit = defineEmits(['refresh', 'longpress']);

// 添加长按处理函数
const onLongPress = (item) => {
  emit('longpress', item, 'more');
};

// 本地事件列表
const localEvents = ref([]);
// 添加加载状态标记，防止重复加载
const isLoading = ref(false);
// 添加上次加载时间标记
const lastLoadTime = ref(0);

// 添加计算属性，判断当前tab是否激活
const isActive = computed(() => {
  return props.currentTab === props.tabIndex;
});

// 计算属性：获取显示的事件列表，优先使用本地数据
const displayEvents = computed(() => {
  return localEvents.value.length > 0 ? localEvents.value : props.events;
});

// 加载事件列表
const loadEvents = async () => {
  // 如果没有联系人ID或者正在加载，则不重复加载
  if (!props.contactId || isLoading.value) {
    console.log('事件tab 跳过加载 - contactId:', props.contactId, 'isLoading:', isLoading.value);
    return;
  }
  
  console.log('事件tab 开始加载数据 - contactId:', props.contactId);
  
  try {
    isLoading.value = true;
    
    const res = await EventApi.queryContactEvents({
      contactId: props.contactId
    });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      // 转换API返回的数据格式为组件需要的格式
      localEvents.value = res.data.map(item => {
        // 获取状态文本和样式类
        const statusTextMap = {
          0: '未完成',
          1: '已完成',
          2: '已放弃'
        };
        
        const statusClassMap = {
          0: 'status-pending',
          1: 'status-completed',
          2: 'status-abandoned'
        };
        
        // 格式化日期
        const formatDate = timestamp => {
          if (!timestamp) return '';
          const date = new Date(timestamp);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}`;
        };
        
        return {
          ...item,
          // UI展示所需的额外字段
          img: '', // 默认头像为空
          name: '发起人', // 默认发起人名称
          type: item.categoryName || getCategoryName(item.categoryId),
          title: item.eventName,
          description: item.eventContent,
          status: statusTextMap[item.dealStatus] || '未完成',
          statusClass: statusClassMap[item.dealStatus] || 'status-pending',
          date: formatDate(item.eventDate)
        };
      });
      
      // 记录本次加载时间
      lastLoadTime.value = Date.now();
      
      console.log('事件tab 数据加载成功，共', localEvents.value.length, '条记录');
      
      // 通知父组件刷新完成
      emit('refresh');
    } else {
      localEvents.value = [];
      console.log('事件tab 数据加载失败:', res.msg);
      uni.showToast({
        title: res.msg || '获取事件列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取事件列表失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 修改 onShow 生命周期钩子，确保每次显示时都能刷新数据
onShow(() => {
  console.log('事件tab onShow - currentTab:', props.currentTab, 'tabIndex:', props.tabIndex, 'isActive:', isActive.value);
  // 只有当该组件真正显示（当前tab激活）且有联系人ID时才执行加载
  if (props.contactId && isActive.value) {
    loadEvents();
  }
});

// 暴露方法给父组件调用
defineExpose({
  loadEvents
});

// 点击事件卡片，跳转到事件编辑页面
const onEventClick = (event) => {
  uni.navigateTo({
    url: `/pages/contact/event-edit?id=${event.id}&contactId=${event.contactId || props.contactId || ''}&mode=edit&contactName=${encodeURIComponent(event.name)}&contactImg=${encodeURIComponent(event.img || '')}`
  });
};

// 添加新事件
const addEvent = () => {
  uni.navigateTo({
    url: `/pages/contact/event-edit?contactId=${props.contactId || ''}&mode=add`
  });
};

// 根据事件类型获取对应图标
const getEventIcon = (type) => {
  const iconMap = {
    '读书': 'bookfill',
    '唱K': 'mic',
    '礼物': 'gift'
  };
  
  return iconMap[type] || '';
};

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  // 如果没有categoryId，返回默认值
  if (!categoryId) return '读书';
  
  // 这里可以添加从本地缓存获取分类名称的逻辑
  // 例如：从uni.getStorageSync('eventCategories')中查找对应的分类名称
  const categories = uni.getStorageSync('eventCategories');
  if (categories && Array.isArray(categories)) {
    const category = categories.find(item => item.id === categoryId);
    if (category) return category.name;
  }
  
  // 如果没有找到，返回默认值
  return '读书';
};

// 根据状态获取样式类名
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-pending',    // 未完成
    1: 'status-completed',  // 已完成
    2: 'status-abandoned'   // 已放弃
  };
  
  return classMap[status] || '';
};

// 根据状态获取文本
const getStatusText = (status) => {
  const textMap = {
    0: '未完成',
    1: '已完成',
    2: '已放弃'
  };
  
  return textMap[status] || '未完成';
};

// 格式化事件日期
const formatEventDate = (timestamp) => {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 格式化提醒信息
const formatReminder = (event) => {
  if (event.reminderEnabled !== 1) return '不提醒';
  
  const days = event.advanceReminderDays || 0;
  const time = event.advanceReminderTime ? event.advanceReminderTime.substring(0, 5) : '09:00';
  
  if (days === 0) {
    return `当天 ${time}`;
  } else {
    return `提前${days}天 ${time}`;
  }
};

// 获取重复类型文本
const getRepeatTypeText = (repeatType) => {
  const typeMap = {
    0: '不重复',
    1: '每天',
    2: '每周',
    3: '每月',
    4: '每年'
  };
  
  return typeMap[repeatType] || '不重复';
};

// 处理图片加载错误
const handleImageError = (event) => {
  // 图片加载失败时，将图片地址置空
  event.img = '';
};

</script>

<style lang="scss" scoped>
.event-container {
  padding: 20rpx 0;
  background-color: #f5f5f5;
  min-height: 100%;
  position: relative; /* 添加相对定位 */
}

.event-card {
  margin: 0 20rpx 20rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20rpx 24rpx;
}

.event-title {
  font-size: 16px;
  color: #007AFF;
  font-weight: 500;
  flex: 1;
  margin-right: 20rpx;
}

.event-tags {
  display: flex;
  gap: 12rpx;
}

.event-tag {
  display: flex;
  align-items: center;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-size: 12px;
  gap: 4rpx;
}

.type-tag {
  background-color: #F0F7FF;
  color: #007AFF;
}

.status-pending {
  background-color: #FFF0F0;
  color: #FF5252;
}

.status-abandoned {
  background-color: #F5F5F5;
  color: #666;
}

.status-completed {
  background-color: #F0FFF0;
  color: #4CAF50;
}

.event-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 24rpx;
  border-top: 1px solid #f0f0f0;
}

.event-time {
  font-size: 12px;
  color: #999;
}

.event-participants {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 12px;
  color: #999;
}

/* 空数据提示 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 添加浮动按钮样式 */
.add-button {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #007AFF;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
  z-index: 10;
}

/* 添加提醒和重复类型样式 */
.event-info {
  display: flex;
  gap: 16rpx;
}

.event-reminder, .event-repeat {
  display: flex;
  align-items: center;
  gap: 4rpx;
  font-size: 12px;
  color: #999;
}

.event-content {
  padding: 0 24rpx 16rpx;
}

.event-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}
</style>
